#!/usr/bin/env node

const mysql = require('mysql2/promise'),
      log   = console.log,
      Koa   = require('koa'),
      app   = new Koa(),
      Router = require('koa-router'),
      router = new Router(),
      fs    = require('fs'),
      path  = require('path'),
      cors  = require('koa2-cors'),
      http  = require('http'),
      https = require('https');

const options = {
    key:fs.readFileSync(path.join(__dirname,'../fourgoldhua.cn.key')),
    cert:fs.readFileSync(path.join(__dirname,'../fourgoldhua.cn.crt'))
}

app.use(cors({
    origin: function (ctx) {
      if (ctx.url === '/test') {
        return "*"; // 允许来自所有域名请求
      }
      return 'http://localhost:8080'; // 这样就能只允许 http://localhost:8080 这个域名的请求了
    },
    exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
    maxAge: 5,
    credentials: true,
    allowMethods: ['GET', 'POST', 'DELETE'],
    allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}))

router.get('/test/api',async (ctx) => {
    let arr = await getAreas();
    if(arr.length == 0){
      console.log('shikongde');
    }
    console.log(arr);
    log('得到数据');
    ctx.body = JSON.stringify(arr);
})

router.get('/test',async (ctx) => {
    ctx.body = '这里是李金桀帅哥哦';
})

let con = mysql.createPool({
    host:'154.8.156.240',
    port:'2020',
    user:'root',
    password:'Ljj0222.',
    database:'tuijian'
});

getAreas();

process.on('unhandledRejection',(reason,p) => {
    console.log('Unhandled Rejection at:Promise',p,'reason:',reason);
});

async function getAreas(){
    const sql = 'select id from user_table where id = 2020000;';
    let [rows] = await con.execute(sql);
    return rows;
}

(async function(){
    log(await getAreas());
})();

app.use(router.routes())
   .use(router.allowedMethods());
app.listen(3004);

//https.createServer(options,app.callback()).listen(2223);
